﻿using DeHeng_Mes.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

public static class SharedFolderAccess
{
    /// <summary>
    /// 连接到共享文件夹
    /// </summary>
    /// <param name="sharedFolderPath">共享文件夹路径</param>
    /// <param name="username">访问共享文件夹的用户名</param>
    /// <param name="password">访问共享文件夹的密码</param>
    /// <returns>连接成功返回 true，否则返回 false</returns>
    public static async Task<bool> ConnectToSharedFolderAsync(string sharedFolderPath, string username, string password)
    {
        try
        {
            ProcessStartInfo psi = new ProcessStartInfo("net", $"use {sharedFolderPath} /user:{username} {password}")
            {
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            using (Process process = Process.Start(psi))
            {
                // 异步等待进程结束
                // 异步等待进程退出
                await Task.Run(() => process.WaitForExit());

                // 异步读取输出
                string output = await process.StandardOutput.ReadToEndAsync();

                // 检查是否成功连接
                if (Directory.Exists(sharedFolderPath))
                {
                    return true;
                }
                else
                {
                    Tools.ProduceLogTextError($"连接共享文件夹失败: {sharedFolderPath}");
                    return false;
                }
            }
        }
        catch (Exception ex)
        {
            Tools.ProduceLogTextError("连接共享文件夹失败: " + ex.Message);
            return false;
        }
    }


    /// <summary>
    /// 断开共享文件夹连接
    /// </summary>
    /// <param name="sharedFolderPath">共享文件夹路径</param>
    public static void DisconnectFromSharedFolder(string sharedFolderPath)
    {
        try
        {
            // 使用 net use /delete 命令断开共享文件夹连接
            ProcessStartInfo psiDisconnect = new ProcessStartInfo("net", $"use {sharedFolderPath} /delete")
            {
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            using (Process process = Process.Start(psiDisconnect))
            {
                process.WaitForExit();
                string output = process.StandardOutput.ReadToEnd();
                Tools.ProduceLogText("断开共享文件夹连接: " + output);
            }
        }
        catch (Exception ex)
        {
            Tools.ProduceLogTextError("断开共享文件夹连接失败: " + ex.Message);;
        }
    }

    /// <summary>
    /// 获取共享文件夹中的文件列表
    /// </summary>
    /// <param name="sharedFolderPath">共享文件夹路径</param>
    public static void ListFilesInSharedFolder(string sharedFolderPath)
    {
        if (Directory.Exists(sharedFolderPath))
        {
            string[] files = Directory.GetFiles(sharedFolderPath);
            foreach (string file in files)
            {
                Tools.ProduceLogText(file);
            }
        }
        else
        {
            Tools.ProduceLogTextError("共享文件夹不存在或不可访问。");
        }
    }
    /// <summary>
    /// 将修改时间在当前时间之前一分钟后的文件复制到指定的本地目录
    /// </summary>
    /// <param name="sharedFolderPath">共享文件夹路径</param>
    /// <param name="savePath">本地保存文件夹路径</param>
    /// <returns>复制的文件路径列表</returns>
    public static async Task<List<string>> CopyRecentFilesToLocalAsync(string sharedFolderPath, string savePath)
    {
        List<string> destFiles = new List<string>();
        try
        {
            if (!Directory.Exists(sharedFolderPath))
            {
                Tools.ProduceLogTextError("共享文件夹不存在或不可访问。");
                return null;
            }

            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath); // 创建保存目录
            }

            string[] files = Directory.GetFiles(sharedFolderPath);
            DateTime currentTime = DateTime.Now;
            DateTime oneMinuteAgo = currentTime.AddMinutes(-1); // 当前时间的前一分钟

            foreach (string file in files)
            {
                FileInfo fileInfo = new FileInfo(file);
                if (fileInfo.LastWriteTime >= oneMinuteAgo)
                {
                    string destFile = Path.Combine(savePath, fileInfo.Name);
                    destFiles.Add(destFile);

                    // 异步复制文件
                    await Task.Run(() => File.Copy(file, destFile, true));
                }
            }

            return destFiles;
        }
        catch (Exception ex)
        {
            Tools.ProduceLogTextError("复制文件失败: " + ex.Message);
            return null;
        }
    }


    /// <summary>
    /// 将修改时间在当前时间之前一分钟后的文件夹复制到指定的本地目录
    /// </summary>
    /// <param name="sharedFolderPath">共享文件夹路径</param>
    /// <param name="savePath">本地保存文件夹路径</param>
    /// <returns>复制的文件夹路径列表</returns>
    public static async Task CopyRecentDirectoriesToLocalAsync(string sharedFolderPath, string savePath)
    {
        List<string> destDirectories = new List<string>();
        try
        {
            if (!Directory.Exists(sharedFolderPath))
            {
                Tools.ProduceLogTextError("共享文件夹不存在或不可访问。");
                return;
            }

            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath); // 创建保存目录
            }

            string[] directories = Directory.GetDirectories(sharedFolderPath);
            DateTime currentTime = DateTime.Now;
            DateTime oneMinuteAgo = currentTime.AddMinutes(-1); // 当前时间的前一分钟

            foreach (string directory in directories)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(directory);
                if (dirInfo.LastWriteTime >= oneMinuteAgo)
                {
                    string destDirectory = Path.Combine(savePath, dirInfo.Name);

                    // 异步创建目标文件夹
                    if (!Directory.Exists(destDirectory))
                    {
                        Directory.CreateDirectory(destDirectory);
                    }

                    // 复制文件夹中的所有文件
                    string[] files = Directory.GetFiles(directory);
                    var copyTasks = new List<Task>();

                    foreach (string file in files)
                    {
                        string destFile = Path.Combine(destDirectory, Path.GetFileName(file));

                        // 异步复制文件
                        copyTasks.Add(Task.Run(() => File.Copy(file, destFile, true)));
                    }

                    // 等待所有文件复制完成
                    await Task.WhenAll(copyTasks);

                    Tools.ProduceLogText($"将文件夹从 {dirInfo.Name} 复制到 {savePath}");
                }
            }
        }
        catch (Exception ex)
        {
            Tools.ProduceLogTextError("复制文件夹失败: " + ex.Message);
        }
    }
    /// <summary>
    /// 将文件从一个文件夹复制到另一个文件夹
    /// </summary>
    /// <param name="sourceFolderPath"></param>
    /// <param name="destinationFolderPath"></param>
    /// <returns></returns>
    public static async void CopyCsvFilesWithSuffixAndDeleteAsync(string sourceFolderPath, string destinationFolderPath, string suffix)
    {
        try
        {
            if (!Directory.Exists(sourceFolderPath))
            {
                Tools.ProduceLogTextError("源文件夹不存在。");
                return;
            }

            if (!Directory.Exists(destinationFolderPath))
            {
                Directory.CreateDirectory(destinationFolderPath); // 如果目标文件夹不存在，则创建
            }

            List<Task> copyTasks = new List<Task>();

            // 遍历源文件夹中的所有 CSV 文件，筛选文件名或内容包含 "Prozessdaten"
            foreach (var filePath in Directory.GetFiles(sourceFolderPath, "*.csv"))
            {
                string fileName = Path.GetFileName(filePath);

                // 判断文件名或文件内容是否包含 "Prozessdaten"
                if (fileName.Contains(suffix))
                {
                    string destFilePath = Path.Combine(destinationFolderPath, fileName);

                    // 异步复制符合条件的 CSV 文件
                    copyTasks.Add(Task.Run(() => File.Copy(filePath, destFilePath, true)));
                }
            }

            // 等待所有文件复制任务完成
            await Task.WhenAll(copyTasks);

            // 复制完成后删除源文件夹中符合条件的 CSV 文件
            foreach (var filePath in Directory.GetFiles(sourceFolderPath, "*.csv"))
            {
                string fileName = Path.GetFileName(filePath);

                if (fileName.Contains(suffix))
                {
                    File.Delete(filePath);
                }
            }
        }
        catch (Exception ex)
        {
            Tools.ProduceLogTextError($"操作失败: {ex.Message}");
        }
    }


}
